package com.dyson.concurrent.audition.demo05;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 生产者消费者模式
 * 使用线程安全的队列实现
 * <p>
 * 正确实现
 */
public class ProducerAndConsumerTest02 {

    private static BlockingQueue<Integer> blcQ = new ArrayBlockingQueue<>(10000);

    public static void main(String[] args) throws InterruptedException {
        // 生产者线程
        Producer p1 = new Producer(blcQ);
        Producer p2 = new Producer(blcQ);
        Producer p3 = new Producer(blcQ);

        Consumer c1 = new Consumer(blcQ);
        Consumer c2 = new Consumer(blcQ);

        p1.start();
        c1.start();
        p2.start();
        p3.start();
        c2.start();

        p1.join();
        p2.join();
        p3.join();
        c1.join();
        c2.join();
        System.out.println("最后的大小是：" + blcQ.size());
    }

    static class Producer extends Thread {
        private BlockingQueue<Integer> blcQ;

        public Producer(BlockingQueue<Integer> blcQ) {
            this.blcQ = blcQ;
        }

        @Override
        public void run() {
            for (int i = 1; i <= 10000; i++) {
                try {
                    blcQ.put(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Consumer extends Thread {
        private BlockingQueue<Integer> blcQ;

        public Consumer(BlockingQueue<Integer> blcQ) {
            this.blcQ = blcQ;
        }

        @Override
        public void run() {
            for (int i = 1; i <= 10000; i++) {
                try {
                    blcQ.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


